<?php

namespace App\Kits\Errors;

use App\Kits\Resources\ApiResource;
use App\Kits\ResponseCode;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;


class BaseException extends \Exception
{
    const DEFAULT_CODE = ResponseCode::CODE_205;
    protected $code = self::DEFAULT_CODE;

    /**
     * 自定义错误处理
     * @param Request $request
     * @param \Throwable $exception
     * @return JsonResponse|mixed
     */
    public static function exceptionHandle(Request $request, \Throwable $exception): ?JsonResponse
    {



        // 数据库回滚
        if ($exception instanceof TransactionException) {
            DB::rollBack();
        }
        // 调用模型的findOrFail 和 firstOrFail方法未找到异常
        if ($exception instanceof ModelNotFoundException) {

            $resource = new ApiResource($exception, NotDataException::DEFAULT_MESSAGE, self::DEFAULT_CODE);
            return $resource->toResponse($request);
        }

        // request 验证不通过抛出的异常，跟框架中 App\Lib\_Error\ValidateException 同名但位置不同
        if ($exception instanceof ValidationException) {
            $errors = $exception->errors();
            if ($errors) {
                $messages = array_pop($errors);
                $message = array_pop($messages);
                $exception->message = $message;
            }
        }
        if ($exception instanceof ThrottleRequestsException) { // 请求次数过多限制（多语言），
            $exception->message = trans($exception->getMessage());
        }
        if ($exception instanceof InvalidArgumentException) { // token不合法
            $exception->message = trans($exception->getMessage());
            $exception->code = 401;
        }



        $resource = new ApiResource($exception);
        return $resource->toResponse($request);

    }
}
